(function () {

	$(function () {
		packager('app.components.form');

		app.components.form = new function () {

			var exports = {};

			exports.init = function () {
				exports.initFileField();
				exports.initSelectField();
				exports.validate();
				exports.initDatetimepicker();

			};

			exports.initFileField = initFileField;
			exports.initSelectField = initSelectField;
			exports.validate = validate;
			exports.initDatetimepicker = initDatetimepicker;

			return exports;
		};
	});

	function initFileField() {
		// disabled state
		$('.form-group').on('click', '.file[disabled]', function (e) {
			e.preventDefault();
		});

		// change event
		$('input[type="file"]').change(function () {
			var filename = '未选择文件';
			var labelId = 'field_' + $(this).attr('name');
			$(this).closest('label').attr('id', 'field_' + $(this).attr('name'));

			if ($(this).get(0).files[0]) {
				filename = $(this).get(0).files[0].name;
				$(this).closest('.form-group').removeClass('has-error');
				$(this).closest('.form-group').find('.help-block').addClass('hidden');
				$(this).closest('.form-group').find('.file-field-style').remove();
			}
			$(this).closest('.form-group').append('<style class="file-field-style">#' + labelId + '.file>span.filename:after{content: "' + filename + '"}</style>');
		});
	}

	// replace native select with select2
	function initSelectField() {

		$('select').each(function () {
			// insert the caret if it does not exist
			var $caret = $('<i class="fa fa-chevron-down"></i>');
			if ($(this).next() != $caret) {
				$(this).after($caret);
			}
			$(this).closest('.form-group').addClass('has-select-tag');
			$(this).select2({
				minimumResultsForSearch: Infinity,
				width: '100%'
			});
		});
	}

	// 初始化表单验证
	function validate() {

		var options = {
			ignore: ".ignore",
			highlight: function (el) {
				$(el).closest('.form-group').addClass('has-error');
				// remove the error message from the server
				$(el).closest('.form-group').find('.help-block').addClass('hidden');
			},
			unhighlight: function (el) {
				$(el).closest('.form-group').removeClass('has-error');
				// remove the error message from the server
				$(el).closest('.form-group').find('.help-block').addClass('hidden');
			},
			errorPlacement: function (error, element) {
				if (element.parent('.input-group').length) {
					error.insertAfter(element.parent());
				} else {
					error.appendTo(element.closest('.form-group'));
				}
			},
			submitHandler: function (form) {

				// disable the submit buttons
				$(form).find('.btn-submit, .btn-save').prop('disabled', true);

				// decide which button to display the state on
				var $clicked = $('.form-submitter.clicked');
				if ($clicked.length) {
					$clicked.html('<i class="fa fa-spinner fa-spin"></i>正在提交...');
					return true;
				}

				// old code, may be removed later
				$(form).find('.btn-submit').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>正在提交...');

				return true;
			}
		};

		$('form:not(".should-manually-validate")').each(function () {
			$(this).validate(options);

			$(this).find('.btn-submit, .btn-save').addClass('form-submitter').on('click', function () {
				$('.form-submitter').removeClass('clicked');
				$(this).addClass('clicked');
			});
		});
	}

	// init datetime picker
	function initDatetimepicker() {
		$('[data-datetimepicker]').each(function () {
			var format = $(this).data('format') ? $(this).data('format') : 'YYYY-MM-DD HH:mm:ss';
			$(this).datetimepicker({
				format: format,
				defaultDate: $(this).val()
			});

			$(this).on('click', function() {
				$(this).data("DateTimePicker").show();
			});
		});
	}

})();